/**
 * 测试AI聊天会话记录功能
 * 
 * 功能测试：
 * 1. 创建会话记录
 * 2. 更新会话记录
 * 3. 获取用户会话列表
 */

const BASE_URL = 'http://localhost:3000';

// 测试数据
const testUserId = 1;
const testChatId = `test_chat_${Date.now()}`;

async function testCreateSession() {
  console.log('\n🧪 测试1: 创建会话记录');
  console.log('==========================================');
  
  try {
    const response = await fetch(`${BASE_URL}/api/chat/sessions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userId: testUserId,
        chatId: testChatId,
        lastMessage: '你好，我想了解一下我的健康状况',
      }),
    });

    const data = await response.json();
    console.log('✅ 创建会话成功:', {
      chatId: data.data.chat_id,
      lastMessage: data.data.last_message,
      userId: data.data.user_id,
    });
    
    return true;
  } catch (error) {
    console.error('❌ 创建会话失败:', error.message);
    return false;
  }
}

async function testUpdateSession() {
  console.log('\n🧪 测试2: 更新会话记录');
  console.log('==========================================');
  
  // 等待1秒，确保时间戳不同
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  try {
    const response = await fetch(`${BASE_URL}/api/chat/sessions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userId: testUserId,
        chatId: testChatId,
        lastMessage: '我最近睡眠质量怎么样？',
      }),
    });

    const data = await response.json();
    console.log('✅ 更新会话成功:', {
      chatId: data.data.chat_id,
      lastMessage: data.data.last_message,
      lastMessageTime: new Date(Number(data.data.last_message_time)).toLocaleString(),
    });
    
    return true;
  } catch (error) {
    console.error('❌ 更新会话失败:', error.message);
    return false;
  }
}

async function testGetSessions() {
  console.log('\n🧪 测试3: 获取用户会话列表');
  console.log('==========================================');
  
  try {
    const response = await fetch(`${BASE_URL}/api/chat/history`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userId: testUserId,
      }),
    });

    const data = await response.json();
    console.log('✅ 获取会话列表成功:');
    console.log(`   总数: ${data.data.total} 条`);
    
    if (data.data.list.length > 0) {
      console.log('\n   最近3条会话:');
      data.data.list.slice(0, 3).forEach((session, index) => {
        console.log(`   ${index + 1}. 标题: ${session.title}`);
        console.log(`      时间: ${new Date(session.updateTime).toLocaleString()}`);
        console.log(`      ChatID: ${session.chatId}`);
        console.log('');
      });
    }
    
    return true;
  } catch (error) {
    console.error('❌ 获取会话列表失败:', error.message);
    return false;
  }
}

async function runTests() {
  console.log('🚀 开始测试AI聊天会话记录功能');
  console.log('==========================================');
  console.log(`测试用户ID: ${testUserId}`);
  console.log(`测试会话ID: ${testChatId}`);
  
  const results = [];
  
  // 执行测试
  results.push(await testCreateSession());
  results.push(await testUpdateSession());
  results.push(await testGetSessions());
  
  // 汇总结果
  console.log('\n📊 测试结果汇总');
  console.log('==========================================');
  const passed = results.filter(r => r).length;
  const total = results.length;
  console.log(`通过: ${passed}/${total}`);
  
  if (passed === total) {
    console.log('✅ 所有测试通过！');
  } else {
    console.log('❌ 部分测试失败，请检查日志');
  }
}

// 运行测试
runTests().catch(console.error);

